package com.real8.plusplayground.client.statistics;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.editor.client.adapters.EditorSource;
import com.google.gwt.editor.client.adapters.ListEditor;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class StatisticsViewer extends Composite implements StatisticsView {
	interface Driver extends
			SimpleBeanEditorDriver<PersonStatistics, StatisticsViewer> {
	}

	private static StatisticsViewerUiBinder uiBinder = GWT
			.create(StatisticsViewerUiBinder.class);

	interface StatisticsViewerUiBinder extends
			UiBinder<Widget, StatisticsViewer> {
	}

	private class LabelSource extends EditorSource<LeafValueEditor<String>> {
		@Override
		public LeafValueEditor<String> create(int index) {
			Label viewer = new Label();
			personsMentionedContainer.insert(viewer, index);
			return viewer.asEditor();
		}

		// TODO investigate if this should be done differently
		// TODO consider retrieving user and displaying some actual info
		// @Override
		// public void dispose(LeafValueEditor<String> subEditor) {
		// subEditor.removeFromParent();
		// }
		//
		// @Override
		// public void setIndex(LeafValueEditor<String> editor, int index) {
		// personsMentionedContainer.insert(editor, index);
		// }
	}

	private final Driver driver = GWT.create(Driver.class);

	private Presenter presenter;

	@UiField
	@Ignore
	TextBox idEditor;

	@UiField
	FlowPanel personsMentionedContainer;

	ListEditor<String, LeafValueEditor<String>> personsMentionedEditor;

	public StatisticsViewer() {
		initWidget(uiBinder.createAndBindUi(this));
		personsMentionedEditor = ListEditor.of(new LabelSource());
		driver.initialize(this);
	}

	@Override
	public void setPresenter(Presenter aPresenter) {
		this.presenter = aPresenter;
	}

	@Override
	public SimpleBeanEditorDriver<PersonStatistics, ?> getEditorDriver() {
		return driver;
	}

	@Override
	public void setId(String personId) {
		idEditor.setValue(personId);
	}

	@UiHandler("idEditor")
	void onIdEditorKeyPress(KeyPressEvent event) {
		// check for return
		int keyCode = event.getNativeEvent().getKeyCode();
		if (keyCode == 13) {
			doIdChange();
		}
	}

	private void doIdChange() {
		if (presenter != null) {
			String id = idEditor.getValue();

			presenter.onIdChange(id);
		}
	}
}
